package org.ala.tcp_feign_server.spring;

import java.lang.reflect.Method;
import java.util.Map;

import org.ala.tcp_feign_common.config.TcpFeignConfigure;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_common.spring.annotations.TcpFeignService;
import org.ala.tcp_feign_server.context.TcpFeignServerContext;
import org.slf4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * tcp-feign 服务端初始化
 * 
 * @author 骆毅(ala)
 * @date 2024年4月20日
 */
@Component
public class TcpFeignServiceInitializer implements ApplicationContextAware, EnvironmentAware {

	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "server");
	
	
	protected ApplicationContext applicationContext;
	/**
	 * 配置
	 */
	protected TcpFeignConfigure configure;

	
	@Override
	public void setEnvironment(Environment environment) {
		configure = TcpFeignConfigure.build(environment);
		
		//	初始化环境
		TcpFeignServerContext.instance().init(configure);
	}


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		
		//	扫描所有TcpFeignContext的注解bean
		scanTcpFeignService();
		
		//	启动netty
		launchGenshinImpact();
	}


	/**
	 * 扫描所有TcpFeignService注解的bean，给TcpFeignContext注册MethodMapper
	 */
	protected void scanTcpFeignService() {
		Map<String, Object> beans = applicationContext.getBeansWithAnnotation(TcpFeignService.class);
		beans.forEach((beanName, bean) -> {
			initExecutor(bean);
		});
	}
	/**
	 * 注册mapper和私有线程池
	 */
	protected void initExecutor(Object bean) {
		TcpFeignService anno = bean.getClass().getAnnotation(TcpFeignService.class);
		//	如果anno注册了私有线程池信息
		if (anno.coreSize() > 0 && anno.maxSize() > 0 && anno.queueSize() > 0) {
			TcpFeignServerContext.instance().getExecutorThreadPool().createDedicated(bean, anno.coreSize(), anno.maxSize(), anno.queueSize());
		}
		//	根url
		String path = anno.path();
		if (StringUtils.isEmpty(path)) {path = "/";}
		else {
			if (!path.startsWith("/")) {path = "/" + path;}
			if (path.endsWith("/")) {path = path.substring(0, path.length()-1);}
		}
		
		//	注册methodMapper
		for (Method method : bean.getClass().getMethods()) {
			TcpFeignServerContext.instance().getExecutorMapper().appendExecutor(bean, method, path);
		}
	}
	
	
	/**
	 * 启动netty
	 */
	protected void launchGenshinImpact() {
		TcpFeignServerContext.instance().startServer();
	}

}
